/*
 * *******************************************************************
 *   @项目名称: BHex Android
 *   @文件名称: FuturesRiskLimitDialog.java
 *   @Date: 19-7-30 下午4:48
 *   @Author: ppzhao
 *   @Description:
 *   @Copyright（C）: 2019 BlueHelix Inc.   All rights reserved.
 *   注意：本内容仅限于内部传阅，禁止外泄以及用于其他的商业目的.
 *  *******************************************************************
 */

package io.bhex.app.trade.ui;

import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import com.flyco.tablayout.SegmentTabLayout;
import com.flyco.tablayout.listener.OnTabSelectListener;

import java.util.ArrayList;
import java.util.List;

import io.bhex.app.R;
import io.bhex.baselib.network.Utils.CodeUtils;
import io.bhex.baselib.network.listener.SimpleResponseListener;
import io.bhex.baselib.network.response.ResultResponse;
import io.bhex.baselib.utils.NumberUtils;
import io.bhex.baselib.utils.ToastUtils;
import io.bhex.sdk.enums.ORDER_SIDE;
import io.bhex.sdk.quote.bean.CoinPairBean;
import io.bhex.sdk.quote.bean.FuturensBaseToken;
import io.bhex.sdk.quote.bean.RiskLimitBean;
import io.bhex.sdk.trade.bean.FuturesCreateOrderConfig;
import io.bhex.sdk.trade.bean.FuturesCreateOrderConfigResponse;
import io.bhex.sdk.trade.futures.FuturesApi;

/**
 * 期货风险限额
 */
public class FuturesRiskLimitDialog {
    private OnDialogObserver mDialogObserver;
    private String mOrderSide = ORDER_SIDE.BUY_OPEN.getOrderSide();
    private Context mContext;
    private View mContentView;
    private Dialog bottomDialog;
    private CoinPairBean coinPairBean;

    private OnLoadingObserver mObserver;
    private SegmentTabLayout limitClassTab;
    private FuturensBaseToken baseTokenFutures;
    private List<RiskLimitBean> riskLimits = new ArrayList<RiskLimitBean>();
    private TextView current_limit;
    private TextView current_keep;
    private TextView current_start;
    private TextView lastest_limit;
    private TextView lastest_keep;
    private TextView lastest_start;
    private TextView titleTv;
    private RiskLimitBean selectRiskLimit;

    public interface OnLoadingObserver {
        void showLoading();

        void hideLoading();
    }

    public interface OnDialogObserver {

        void onShow(DialogInterface dialog);

        void onDismiss(DialogInterface dialog);

        void onReqHttpSuccess();

        void onReqHttpFaile();
    }

    public FuturesRiskLimitDialog(Context context, String orderSide, CoinPairBean mCoinPairBean, OnLoadingObserver observer,OnDialogObserver dialogObserver) {
        mContext = context;
        mOrderSide = orderSide;
        coinPairBean = mCoinPairBean;
        mObserver = observer;
        mDialogObserver = dialogObserver;
    }

    public void ShowDialog() {
        bottomDialog = new Dialog(mContext, R.style.BottomDialog);
        mContentView = LayoutInflater.from(mContext).inflate(R.layout.dialog_futures_risk_limit_layout, null);
        bottomDialog.setContentView(mContentView);
        ViewGroup.MarginLayoutParams params = (ViewGroup.MarginLayoutParams) mContentView.getLayoutParams();
        params.width = mContext.getResources().getDisplayMetrics().widthPixels;
//        params.width = mContext.getResources().getDisplayMetrics().widthPixels-PixelUtils.dp2px(24)*2;
//        params.leftMargin = PixelUtils.dp2px(24);
//        params.rightMargin = PixelUtils.dp2px(24);
        mContentView.setLayoutParams(params);
        initView();
        bottomDialog.setCanceledOnTouchOutside(true);
        bottomDialog.getWindow().setGravity(Gravity.BOTTOM);
        bottomDialog.getWindow().setWindowAnimations(R.style.BottomDialog_Animation);
        bottomDialog.setOnShowListener(new DialogInterface.OnShowListener() {
            @Override
            public void onShow(DialogInterface dialog) {
                if (mDialogObserver != null) {
                    mDialogObserver.onShow(dialog);
                }
            }
        });
        bottomDialog.setOnDismissListener(new DialogInterface.OnDismissListener() {
            @Override
            public void onDismiss(DialogInterface dialog) {
                if (mDialogObserver != null) {
                    mDialogObserver.onDismiss(dialog);
                }
            }
        });
        bottomDialog.show();
    }

    private void initView() {
        try {
            if (coinPairBean != null && mContentView != null) {
                titleTv = mContentView.findViewById(R.id.title);
                current_limit = mContentView.findViewById(R.id.current_limit);
                current_keep = mContentView.findViewById(R.id.current_keep);
                current_start = mContentView.findViewById(R.id.current_start);

                lastest_limit = mContentView.findViewById(R.id.lastest_limit);
                lastest_keep = mContentView.findViewById(R.id.lastest_keep);
                lastest_start = mContentView.findViewById(R.id.lastest_start);

                limitClassTab = mContentView.findViewById(R.id.segmentTab);
                limitClassTab.setOnTabSelectListener(new OnTabSelectListener() {
                    @Override
                    public void onTabSelect(int position) {
                        if (riskLimits != null && riskLimits.size() - 1 >= position) {
                            RiskLimitBean riskLimitsBean = riskLimits.get(position);
                            setSelectLimit(riskLimitsBean);
                        }
                    }

                    @Override
                    public void onTabReselect(int position) {

                    }
                });

                mContentView.findViewById(R.id.btnSure).setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        if (coinPairBean != null && selectRiskLimit != null) {
                            setRiskLimit(coinPairBean.getSymbolId(), selectRiskLimit.getRiskLimitId(), mOrderSide);
                        }
                    }
                });

                mContentView.findViewById(R.id.btnCancel).setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        bottomDialog.dismiss();
                    }
                });

                if (mOrderSide.equals(ORDER_SIDE.BUY_OPEN.getOrderSide())) {
                    titleTv.setText(mContext.getString(R.string.string_set_hold_long_risk_limit));
                } else {
                    titleTv.setText(mContext.getString(R.string.string_set_hold_short_risk_limit));
                }

                baseTokenFutures = coinPairBean.baseTokenFutures;
                if (baseTokenFutures != null) {
                    riskLimits.clear();
                    List<RiskLimitBean> riskLimitsAll = baseTokenFutures.getRiskLimits();
                    for (RiskLimitBean riskLimitBean : riskLimitsAll) {
                        riskLimits.add(riskLimitBean);
                    }
                    if (this.riskLimits != null) {
                        String[] riskClasses = new String[this.riskLimits.size()];
                        for (int i = 0; i < riskClasses.length; i++) {
                            RiskLimitBean riskLimitsBean = this.riskLimits.get(i);
                            riskClasses[i] = riskLimitsBean.getRiskLimitAmount();
                        }
                        if (riskClasses.length > 0) {
                            limitClassTab.setTabData(riskClasses);
                            limitClassTab.setCurrentTab(0);//默认是增加保证金
                        }
                    }
                }
                getFuturesCreateOrderConfig();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    /**
     * 设置选择的风险限额
     *
     * @param riskLimitsBean
     */
    private void setCurrentLimit(RiskLimitBean riskLimitsBean) {
        if (riskLimitsBean == null) {
            return;
        }
        if (riskLimits != null) {
            for (int i = 0; i < riskLimits.size(); i++) {
                RiskLimitBean itemRisk = riskLimits.get(i);
                if (itemRisk != null) {
                    if (riskLimitsBean.getRiskLimitId().equals(itemRisk.getRiskLimitId())) {
                        if (limitClassTab.getTabCount()>i) {
                            limitClassTab.setCurrentTab(i);
                        }
                        break;
                    }
                }

            }
        }
        current_limit.setText(riskLimitsBean.getRiskLimitAmount() + mContext.getString(R.string.string_futures_unit));
        current_keep.setText(NumberUtils.roundFormat(NumberUtils.mul(riskLimitsBean.getMaintainMargin(), "100"), 2) + "%");
        current_start.setText(NumberUtils.roundFormat(NumberUtils.mul(riskLimitsBean.getInitialMargin(), "100"), 2) + "%");
    }

    /**
     * 设置选择的风险限额
     *
     * @param riskLimitsBean
     */
    private void setSelectLimit(RiskLimitBean riskLimitsBean) {
        if (riskLimitsBean == null) {
            return;
        }
        selectRiskLimit = riskLimitsBean;
        lastest_limit.setText(riskLimitsBean.getRiskLimitAmount() + mContext.getString(R.string.string_futures_unit));
        lastest_keep.setText(NumberUtils.roundFormat(NumberUtils.mul(riskLimitsBean.getMaintainMargin(), "100"), 2) + "%");
        lastest_start.setText(NumberUtils.roundFormat(NumberUtils.mul(riskLimitsBean.getInitialMargin(), "100"), 2) + "%");
    }

    /**
     * 获取下单配置
     */
    private void getFuturesCreateOrderConfig() {
        FuturesApi.getFuturesCreateOrderConfig(coinPairBean.getExchangeId(), coinPairBean.getSymbolId(), new SimpleResponseListener<FuturesCreateOrderConfigResponse>() {
            @Override
            public void onBefore() {
                super.onBefore();
                if (mObserver != null)
                    mObserver.showLoading();
            }

            @Override
            public void onFinish() {
                super.onFinish();
                if (mObserver != null)
                    mObserver.hideLoading();
            }

            @Override
            public void onSuccess(FuturesCreateOrderConfigResponse response) {
                super.onSuccess(response);
                if (CodeUtils.isSuccess(response, true)) {
                    List<FuturesCreateOrderConfig> dataConfigs = response.getArray();
                    if (dataConfigs != null && dataConfigs.size() > 0) {
                        FuturesCreateOrderConfig futuresCreateOrderConfig = dataConfigs.get(0);
                        List<RiskLimitBean> riskLimit = futuresCreateOrderConfig.getRiskLimit();
                        for (RiskLimitBean riskLimitBean : riskLimit) {
                            if (riskLimitBean.getSide().equals(mOrderSide)) {
                                setCurrentLimit(riskLimitBean);
                            }
                        }

                    }
                }
            }

            @Override
            public void onError(Throwable error) {
                super.onError(error);
            }
        });
    }

    /**
     * 设置风险限额
     *
     * @param symbolId
     * @param riskLimitId
     * @param side
     */
    private void setRiskLimit(String symbolId, String riskLimitId, String side) {
        FuturesApi.setRiskLimit(symbolId, riskLimitId, side, new SimpleResponseListener<ResultResponse>() {
            @Override
            public void onBefore() {
                super.onBefore();
                if (mObserver != null)
                    mObserver.showLoading();
            }

            @Override
            public void onFinish() {
                super.onFinish();
                if (mObserver != null)
                    mObserver.hideLoading();
            }

            @Override
            public void onSuccess(ResultResponse response) {
                super.onSuccess(response);
                if (CodeUtils.isSuccess(response, true)) {
                    if (response.isSuccess()) {
                        ToastUtils.showShort(mContext.getString(R.string.string_submit_success));
                        if (mDialogObserver != null) {
                            mDialogObserver.onReqHttpSuccess();
                        }
                        if (bottomDialog != null && bottomDialog.isShowing()) {
                            bottomDialog.dismiss();
                        }
                    } else {
                        ToastUtils.showShort(mContext.getString(R.string.string_submit_failed));
                        if (mDialogObserver != null) {
                            mDialogObserver.onReqHttpFaile();
                        }
                    }
                }
            }

            @Override
            public void onError(Throwable error) {
                super.onError(error);
                ToastUtils.showShort(mContext.getString(R.string.string_submit_failed));
                if (mDialogObserver != null) {
                    mDialogObserver.onReqHttpFaile();
                }
            }
        });
    }
}
